# coding: utf-8
from flask import render_template, redirect, request, url_for, flash
from flask_login import login_user, login_required, logout_user, current_user
from xshare.model.admin import Admin
from flask import Blueprint

index = Blueprint('admin', __name__)


@index.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('admin/login.html')
    else:
        username = request.form.get("username", '')
        password = request.form.get("password", '')
        if not username or not password:
            flash(u'登陆失败！用户名和密码不能为空。', 'danger')
            return render_template('admin/login.html')
        user = Admin.query.filter_by(username=username, is_deleted=0).first()
        if user is not None and user.verify_password(password):
            login_user(user)
            flash(u'登陆成功！欢迎回来，%s!' % user.username, 'success')
            return redirect(url_for('admin.home'))
        else:
            flash(u'登陆失败！用户名或密码错误，请重新登陆。', 'danger')
            return render_template('admin/login.html')


@index.route('/logout')
@login_required
def logout():
    logout_user()
    flash(u'您已退出登陆。', 'success')
    return redirect(url_for('index.login'))


@index.route('/')
def home():
    if current_user.is_authenticated:
        return render_template('admin/index.html')
    else:
        print(url_for('admin.login'))
        return redirect(url_for('admin.login'))
